BVH tree construction
We want to create a binary tree of primitives, with internal nodes spatially represented by AABBs and the actual primitive objects as the leaf nodes.
My construction was recurse over an array of primitive objects. Pseudocode:
buildTree(thisNode, primArray)
if primArray.count == 1 //leaf node
thisNode.type = leaf
thisNode.prim = primArray[0]
return
//split primitives into left and right lists
//make sure these are smaller than primArray!
primArray leftArray, rightArray = split(primArray)
node leftNode, rightNode
buildTree(leftNode, leftArray)
buildTree(rightNode, rightArray)
The simplest split is spatial median. Given an AABB, find the axis with the largest length. Then, split the AABB into two equal regions along the largest axis. Then, divide the primitives into two groups based on which side of the split they lie.
Watch out! When splitting, there can be cases where all primitives end up in one group. In this case, just come up with some split that works towards the base case of one primitive in each group.